package com.example.infrastructure.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.domain.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface UserMapper extends BaseMapper<User> {

    /**
     * 根据用户名查询用户
     */
    @Select("SELECT * FROM sys_user WHERE username = #{username} AND deleted = 0")
    User selectByUsername(@Param("username") String username);

    /**
     * 查询用户的角色ID列表
     */
    @Select("SELECT role_id FROM sys_user_role WHERE user_id = #{userId}")
    List<Long> selectUserRoleIds(@Param("userId") Long userId);

    /**
     * 查询用户的角色列表
     */
    @Select("SELECT r.* FROM sys_role r " +
            "INNER JOIN sys_user_role ur ON r.id = ur.role_id " +
            "WHERE ur.user_id = #{userId} AND r.deleted = 0")
    List<String> selectUserRoles(@Param("userId") Long userId);

    /**
     * 插入用户角色关系
     */
    void insertUserRoles(@Param("userId") Long userId, @Param("roleIds") List<Long> roleIds);

    /**
     * 删除用户角色关系
     */
    void deleteUserRoles(@Param("userId") Long userId);

    /**
     * 批量删除用户角色关系
     */
    void deleteUserRolesByUserIds(@Param("userIds") List<Long> userIds);

    /**
     * 查询用户列表（包含角色信息）
     */
    @Select("SELECT DISTINCT u.*, GROUP_CONCAT(r.name) as role_names " +
            "FROM sys_user u " +
            "LEFT JOIN sys_user_role ur ON u.id = ur.user_id " +
            "LEFT JOIN sys_role r ON ur.role_id = r.id " +
            "WHERE u.deleted = 0 " +
            "GROUP BY u.id")
    List<User> selectUserList();
} 